package com.tool.shiro.service.impl;

import com.tool.shiro.mapper.basic.ShiroPermissionMapper;
import com.tool.shiro.mapper.basic.ShiroRoleMapper;
import com.tool.shiro.mapper.ShiroUserMapper;
import com.tool.shiro.mapper.basic.ShiroRolePermissionMapper;
import com.tool.shiro.mapper.basic.ShiroUserRoleMapper;
import com.tool.shiro.pojo.ShiroPermission;
import com.tool.shiro.pojo.ShiroRole;
import com.tool.shiro.pojo.ShiroUser;
import com.tool.shiro.service.ShiroUserService;
import com.tool.shiro.util.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional			// 事务
public class ShiroUserServiceImpl implements ShiroUserService {

	@Resource
	private ShiroUserMapper shiroUserMapper;

	@Resource
	private ShiroUserRoleMapper shiroUserRoleMapper;

	@Resource
	private ShiroRoleMapper shiroRoleMapper;

	@Resource
	private ShiroRolePermissionMapper shiroRolePermissionMapper;

	@Resource
	private ShiroPermissionMapper shiroPermissionMapper;

	@Override
	public boolean insertUser(ShiroUser shiroUser) {
		String salt = SaltUtils.getSalt(16);
		shiroUser.setSalt(salt);
		Md5Hash md5Hash = new Md5Hash(shiroUser.getPassword(), salt, 1024);
		shiroUser.setPassword(md5Hash.toHex());
		return shiroUserMapper.insertUser(shiroUser) == 1;
	}

	@Override
	public List<ShiroRole> queryRolesByUser(ShiroUser user) {
		// 获取用户对应角色列表id
		List<Integer> roleIdList = shiroUserRoleMapper.queryUserRolesId(user.getId(), "shiro_user");
		// 获取用户所有角色对象
		List<ShiroRole> shiroRoles = shiroRoleMapper.queryRoleByRolesId(roleIdList);
		return shiroRoles;
	}

	@Override
	public ShiroUser queryUser(ShiroUser user) {
		return shiroUserMapper.queryUserByAccount(user.getAccount());
	}

	@Override
	public List<ShiroPermission> queryPermissionsByUser(ShiroUser user) {
		// 获取用户对应角色列表id
		List<Integer> roleIdList = shiroUserRoleMapper.queryUserRolesId(user.getId(), "shiro_user");
		// 获取角色对应权限列表id
		List<Integer> permissionIdList = shiroRolePermissionMapper.queryRolePermissionsId(roleIdList);
		// 获取用户所有权限对象
		List<ShiroPermission> shiroPermissions = shiroPermissionMapper.queryPermissionsByIds(permissionIdList);
		return shiroPermissions;
	}

	@Override
	public boolean updateShiroUser(ShiroUser user) {
		return shiroUserMapper.updateShiroUser(user) == 1;
	}

	@Override
	public boolean deleteShiroUser(ShiroUser user) {
		return shiroUserMapper.deleteShiroUser(user) == 1;
	}
}
